<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    

    <title>{$Think.config.site.title} - 广告管理</title>
    <meta name="keywords" content="{$Think.config.site.keywords}">
    <meta name="description" content="{$Think.config.site.description}">

    <link href="{$Think.config.site.resource_url}css/bootstrap.min.css?v=3.3.5" rel="stylesheet">
    <link href="{$Think.config.site.resource_url}css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
    <link href="{$Think.config.site.resource_url}css/plugins/iCheck/custom.css" rel="stylesheet">
    <link href="{$Think.config.site.resource_url}css/animate.min.css" rel="stylesheet">
    <link href="{$Think.config.site.resource_url}css/style.min.css?v=4.0.0" rel="stylesheet">
    <link href="{$Think.config.site.common_resource_url}js/chosen/chosen.css" rel="stylesheet" type="text/css"/>
</head>

<body class="gray-bg">
    <div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-4">
            <div id="nestable-menu">
                <button type="button" class="btn btn-primary btn-sm" onclick="window.history.back()"><i class="fa fa-backward"></i> 返回</button>
            </div>
        </div>
    </div>
    <input type="hidden" name="brand" value="{if($info['realtion_type']=='brand')}{$info.realtion_content}{/if}">
    <input type="hidden" name="cates" value="{if($info['realtion_type']=='cate')}{$info.realtion_content}{/if}">
    <input type="hidden" name="goods" value="{if($info['realtion_type']=='goods')}{$info.realtion_content}{/if}">
      <form method="get" class="form-horizontal">
      <div class="row">
          <div class="col-sm-7">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>广告信息</h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                      	</div>
                    </div>
                    <div class="ibox-content">
                      
                            <div class="form-group">
                                <label class="col-sm-3 control-label">广告名</label>
                                <div class="col-sm-9">
                                    <input id="adv_name" name="adv_name" class="form-control" type="text" value="{$info['adv_name']}">
                                    <input type="hidden" name="adp_id" value="{$info['adp_id']}">
                                    <input type="hidden" name="adv_id" value="{$info['adv_id']}">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">广告排序</label>
                                <div class="col-sm-9">
                                    <input id="adv_sort" name="adv_sort" class="form-control" type="text" value="{$info['adv_sort']?:0}">

                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">广告简介</label>
                                <div class="col-sm-9">
                                    <textarea id="adv_desc" name="adv_desc" class="form-control">{$info['adv_desc']}</textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">关联商品</label>
                                <div class="col-sm-9">
                                    <select name="realtion_type" class="form-control realtion_type">
                                        <option value="0" {if($info['realtion_type'] == 0)} selected="selected" {/if}>无</option>
                                        <option value="brand" {if($info['realtion_type'] == 'brand')} selected="selected" {/if}>关联品牌 (需在右侧选择品牌)</option>
                                        <option value="cate" {if($info['realtion_type'] == 'cate')} selected="selected" {/if}>关联分类 (需在右侧选择分类)</option>
                                        <option value="goods" {if($info['realtion_type'] == 'goods')} selected="selected" {/if}>自定义商品   (需在右侧添加商品)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">状  态：</label>
                                <div class="col-sm-9">
                                	<label for="statustrue">开启</label>
                                    <input id="statustrue" name="adv_status" class="form-control"  type="radio" value="1" {if($info['adv_status']==1)} checked {/if}>
                                    <label for="statusfalse">关闭</label>
                                    <input id="statusfalse" name="adv_status" class="form-control"  type="radio" value="0" {if($info['adv_status']==0)} checked {/if}>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">开始时间</label>
                                <div class="col-sm-9">
                                    <input id="start_time" name="start_time" class="form-control laydate-icon" type="text" value="{$info['start_time']}">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-3 control-label">结束时间</label>
                                <div class="col-sm-9">
                                    <input id="end_time" name="end_time" class="form-control laydate-icon" type="text" value="{$info['end_time']}">
                                </div>
                            </div>

                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <div class="col-sm-5 col-sm-offset-3">
                                    <input type="submit" class="btn btn-primary" value="提交">
                                </div>
                            </div>
                        
                    </div>
                </div>
            </div>
            <div class="col-sm-5">
				<div class="ibox float-e-margins">
					<div class="ibox-title">
						<h5>广告图片</h5> 
						<div class="ibox-tools">
							<a class="collapse-link">
							<i class="fa fa-chevron-up"></i>
							</a>
						</div>
					</div>
					<div class="ibox-content" style="overflow: hidden; padding: 10px 0;">
                        <div class="col-sm-6">
						<p>
							<button type="button" class="btn btn-primary btn-sm col-sm-12" up-img="adv_thumb" id="adv_thumb" url="{:url('Upload/upimg')}" auto='true' success="upthumb" error="uperror" value="{$info['adv_thumb']}">上传缩略图</button>
						</p>
						<p><img id="show_adv_thumb" alt="image"  src="{$info['adv_thumb']}" style="max-width: 100%;" /></p>
                        </div>
                        <div class="col-sm-6">
                        <p>
                            <button type="button" class="btn btn-primary btn-sm col-sm-12" up-img="adv_img" id="adv_img" url="{:url('Upload/upimg')}" auto='true' success="upsuccess" error="uperror" value="{$info['adv_img']}">上传大图</button>
                        </p>
                        <p><img id="show_adv_img" alt="image"  src="{$info['adv_img']}" style="max-width: 100%;" /></p>
                        </div>
					</div>
				</div>

                <div class="ibox float-e-margins realtion_content" style="display: none;">
                    <div class="ibox-title">
                        <h5 class="c_title"></h5> 
                        <div class="ibox-tools">
                            <a class="collapse-link">
                            <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        
                    </div>
                </div>
          </div>
        </div>
        </form>
    </div>

    <script src="{$Think.config.site.resource_url}js/jquery.min.js?v=2.1.4"></script>
    <script src="{$Think.config.site.resource_url}js/bootstrap.min.js?v=3.3.5"></script>
    <script src="{$Think.config.site.resource_url}js/content.min.js?v=1.0.0"></script>
    <script src="{$Think.config.site.resource_url}js/plugins/validate/jquery.validate.min.js"></script>
    <script src="{$Think.config.site.resource_url}js/plugins/validate/messages_zh.min.js"></script>
  	<script src="{$Think.config.site.resource_url}js/plugins/layer/layer.js"></script>
  	<script src="{$Think.config.site.resource_url}js/plugins/iCheck/icheck.min.js"></script>
  	<script src="{$Think.config.site.common_resource_url}js/majax.js"></script>
  	<script src="{$Think.config.site.common_resource_url}js/laydate/laydate.js"></script>
    <script type="text/javascript" src="{$Think.config.site.common_resource_url}js/chosen/chosen.jquery.js"></script>
</body>

</html>
<script>

var init = 0;

function upsuccess(d){
    if (d.code>0) {
        $('#show_adv_img').attr('src',d.data);
    }else{
        layer.msg(d.msg, {icon: 5});
    }
}
function upthumb(d){
    if (d.code>0) {
        $('#show_adv_thumb').attr('src',d.data);
    }else{
        layer.msg(d.msg, {icon: 5});
    }
}

function uperror(e){
	layer.msg('网络出错！', {icon: 5});
}

var realtion_brand = $('input[name="brand"]').val().split(',');
var realtion_cates = $('input[name="cates"]').val().split(',');
var realtion_goods = $('input[name="goods"]').val().split(',');
$('.realtion_type').change(function(){
    var type = $(this).find('option:selected').val(),o = $('.realtion_content'),o_title = o.find('.c_title'),o_content = o.find('.ibox-content');
    if (type==0) {o.hide(); return false;}  o.show();
    o_content.html('');
    if (type=='brand') {
        o_title.text('请选择品牌');
        //获取品牌数据
        majax('{:url("Goodsbrand/index")}',{},function(res){
            var brands = res.data,str = '<select name="brands[]" class="form-control" id="brands" multiple="multiple">';
            for (var i = 0; i < brands.length; i++) {
                str += '<option value="'+brands[i].brand_id+'"';
                if ($.inArray(brands[i].brand_id.toString() ,realtion_brand) > -1) {
                    str += ' selected="selected" ';
                }
                str += '>'+brands[i].brand_name+'</option>';
            }
            str += '<select>';
            o_content.append(str);
            $("#brands").chosen({no_results_text: "没有找到："});
            $("#brands").trigger("chosen:updated");
        })

    }else if (type=='cate') {
        o_title.text('请选择分类');
        //获取分类数据
        majax('{:url("Goodscate/index")}',{},function(res){
            var cates = res.data.cate_tree,str = '<select name="cates[]" class="form-control" id="cates" multiple="multiple">';
            for (var i = 0; i < cates.length; i++) {
                str += '<option '+ ((cates[i].cate_pid==0)?' disabled="disabled" ':'') +' value="'+cates[i].cate_id+'"';
                if ($.inArray(cates[i].cate_id.toString() ,realtion_cates) > -1) {
                    str += ' selected="selected" ';
                }

                str += '>'+cates[i].fullname+'</option>';
            }
            str += '<select>';
            o_content.append(str);
            $("#cates").chosen({no_results_text: "没有找到："});
            $("#cates").trigger("chosen:updated");
        })
    }else if (type=='goods') {
        o_title.text('请选择商品');
        var str = '<div class="row"><button type="button" class="btn btn-primary btn-sm col-sm-12 addgoods">添加商品</button> </div>\
                    <div class="row">\
                        <div class="table-responsive">\
                            <table class="table table-striped" id="listtable">\
                                <thead>\
                                    <tr>\
                                        <th width="">商品图片</th>\
                                        <th width="">商品名称</th>\
                                        <th width="">价格</th>\
                                        <th width="">销量</th>\
                                        <th width="">操作</th>\
                                    </tr>\
                                </thead>\
                                <tbody></tbody>\
                            </table>\
                        </div>\
                    </div>';
        o_content.append(str);
        openaddgoods();
    }else{
        o.hide();
        return false
    }
})

$('body').delegate('.addgoods','click',function(){
    openaddgoods();
})

function openaddgoods(){
    var goods=[];
    if (init==0) {
        majax('{:url("addGoods")}',{ids:realtion_goods.join(',')},function(res){
            var d = res.data;
            for (var i = d.length - 1; i >= 0; i--) {
                id=d[i].goods_id, 
                img=d[i].picture,
                name=d[i].goods_name,
                price=d[i].min_price+'-'+d[i].max_price,
                sales=d[i].sales;
                goods.push({id:id,img:img,name:name,price:price,sales:sales});
            }
            addGoods(goods);
            init++;
        });
    }else{
        var ids=realtion_goods;
        //获取已选择的
        $('#listtable tbody tr').each(function(){
            ids.push($(this).data('id'));
        })

        layer_font = layer.open({
            type: 2,
            title: '添加商品',
            shadeClose: false,
            shade: 0.8,
            area: ['1000px', '90%'],
            content: '{:url("addGoods",'','')}?ids='+ids.join(','), //iframe的url
            btn:['确定','取消'],
            btn1: function(index, layero){
                var d = $('iframe',layero)[0].contentDocument;
                $(".tr_goods",d).each(function(){
                    id=$(this).data('id'), 
                    img=$(this).find('img').attr('src'),
                    name=$(this).find('.goodsname').text(),
                    price=$(this).find('.price').text(),
                    sales=$(this).find('.sales').text();
                    goods.push({id:id,img:img,name:name,price:price,sales:sales});
                })
                addGoods(goods);
            }
        });
    }
}


function addGoods(re){
   $('#listtable tbody').html('');
   var str = '';
   for (var i = re.length - 1; i >= 0; i--) {
       str +='<tr data-id="'+re[i].id+'" id="goods_'+re[i].id+'" class="tr_goods">\
                <td><img src="'+re[i].img+'" width="30" height="30"></td>\
                <td class="goodsname">'+re[i].name+'</td>\
                <td class="price">'+re[i].price+'</td>\
                <td class="sales">'+re[i].sales+'</td>\
                <td><input type="hidden" name="goods[]" value="'+re[i].id+'" >\
                <button type="button" class="btn btn-primary btn-xs delleft">&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;</button></td>\
            </tr>';
   }
    $('#listtable tbody').append(str);
}

$('body').delegate('.delleft','click',function(){
    var id = $(this).closest('tr').data('id');
    for (var i = realtion_goods.length - 1; i >= 0; i--) {
        if(realtion_goods[i] == id){
            realtion_goods.splice(i,1);
        }
    }
    $(this).closest('tr').remove();
})

$(document).ready(function(){
    $('.realtion_type').change();
	var start = {
		elem: '#start_time',
		format: 'YYYY-MM-DD hh:mm:ss',
		// min: laydate.now(), //设定最小日期为当前日期
		max: '2099-06-16 23:59:59', //最大日期
		istime: true,
		istoday: true,
		choose: function(datas){
			end.min = datas; //开始日选好后，重置结束日的最小日期
			end.start = datas //将结束日的初始值设定为开始日
		}
	};
	var end = {
		elem: '#end_time',
		format: 'YYYY-MM-DD hh:mm:ss',
		// min: laydate.now(),
		max: '2099-06-16 23:59:59',
		istime: true,
		istoday: true,
		choose: function(datas){
			start.max = datas; //结束日选好后，重置开始日的最大日期
		}
	};
	laydate.skin('molv'); 
	laydate(start);
	laydate(end);
	laydate.reset(); 

	
	$("input").iCheck({checkboxClass:"icheckbox_square-green",radioClass:"iradio_square-green",});

	$("form").validate({
	  debug:true,
	  submitHandler:function(form){
            save();   
      },    
	  rules: {
		adv_name: {
		  required: true,
		},

		adv_key: {
		  required: true,
		},

        adv_sort: {
            number:true,
        }
		
	  },
	  messages: {
		adv_name: {
		  required: '广告名必须填写',
		},

		adv_key: {
		  required: '广告标识必须填写',
		},
		adv_sort: {
            number:'只能输入数字',
        }
	  }
	});

	function save(){
		var fomrData = $("form").serialize();

		majax('{:url("editadv")}',fomrData,function(d){
			if (d.code>0) {
				// window.parent.editSuccess(d);
			}else{
				layer.msg(d.msg, {icon: 5});
			}
		})
	};
})
</script>